package com.wtb.javatool.service.impl;


import com.wtb.javatool.dao.AdministratorsMapper;
import com.wtb.javatool.dao.SelfBuiltDatabaseMapper;
import com.wtb.javatool.dao.TciMapper;
import com.wtb.javatool.entity.Administrators;
import com.wtb.javatool.entity.SelfBuiltDatabase;
import com.wtb.javatool.entity.Tci;
import com.wtb.javatool.service.ISelfBuiltDatabaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class SelfBuiltDatabaseService implements ISelfBuiltDatabaseService {

    @Autowired
    private SelfBuiltDatabaseMapper selfBuiltDatabaseMapper;
    @Autowired
    private TciMapper tciMapper;
    @Autowired
    private AdministratorsMapper administratorsMapper;

    public Integer applyByCourse(SelfBuiltDatabase selfBuiltDatabase){
        //根据courseId(JXBMC)查询tci表获取课程号(PK_ID)和学期号(KCDM)
        Tci tci = tciMapper.selectByJxbmc(
                selfBuiltDatabase.getCourseId(),
                selfBuiltDatabase.getApproverId()
        );
        if (tci == null) {
            System.out.println("tci is null");
            return 0;
        }

        String kechenghao = tci.getPK_ID();
        String xueqihao = tci.getXQ();
        //获得databaseName
        String databaseName = generateDatabaseName(selfBuiltDatabase.getCourseId(), kechenghao, xueqihao, selfBuiltDatabase.getStudentId());
        //保存到申请表对应对象中
        selfBuiltDatabase.setDatabaseName(databaseName);


        //查询管理员ID
        Administrators administrators = administratorsMapper.selectAdministratorsName();
        //测试是否为空
        if(administrators == null){
            System.out.println("administrators is null");
            return 0;
        }
        //将管理员ID存入申请表对应对象中
        selfBuiltDatabase.setAuthorizerId(administrators.getAdministratorName());
        return selfBuiltDatabaseMapper.applyByCourse(selfBuiltDatabase);
    }

    public List<SelfBuiltDatabase> status(){
        return selfBuiltDatabaseMapper.status();
    }

    private String generateDatabaseName(String courseId, String approverId,
                                        String xueqihao, String studentId) {
        // 将中文转换为拼音，这里简化为直接使用原字符串，实际应用中应使用拼音转换工具
        String courseIdPinyin = convertToPinyin(courseId);
        String approverIdPinyin = convertToPinyin(approverId);

        return String.format("%s_%s_%s_stu_%s",
                courseIdPinyin, approverIdPinyin, xueqihao, studentId);
    }
    private String convertToPinyin(String chinese) {
        // 实际应用中应使用拼音转换工具如pinyin4j
        // 这里简化为去除空格和特殊字符
        return chinese.replaceAll("[^a-zA-Z0-9]", "").toLowerCase();
    }

    public List<Tci> tci(){
        return tciMapper.tci();
    }
}
